package com.springvision.yuanfeng.core.tcp;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.springvision.core.tcpclient.TcpClient;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;

/**
 * @author qwh
 * @since 2017/6/26 14:16
 */
//@Component
@Lazy(false)
public class YfTCPClient extends TcpClient {

	public YfTCPClient() throws InterruptedException {
		super();
	}

	public Channel createConnect() throws InterruptedException {
		return new TcpClient().getChannel();// 开启连接
	}

	/**
	 * 执行tcp发送
	 *
	 * @param task
	 * @return
	 * @throws InterruptedException
	 */
	// public String send(Channel channel, String msg) throws
	// InterruptedException {
	// String channelId = channel.id().asLongText();
	// channel.writeAndFlush(msg);// 执行tcp下发
	// return channelId;
	// }

	public void send(String msg) throws InterruptedException {
		ByteBuf message = null;
		if (channel != null && channel.isActive()) {
			try {
				System.out.println("8400---write----");
				message = Unpooled.buffer(msg.length());
				message.writeBytes(msg.getBytes());
				channel.writeAndFlush(message).sync();
				System.out.println("8400---end----");
			} catch (Throwable e) {
				e.printStackTrace();
			}
		} else {
			System.err.println("Client:Channel Error...");
		}
	}

}
